package impl

import (
	"context"
	"fmt"

	"gitee.com/lishixi/gops/vblog/apps/blog"
	"gitee.com/lishixi/gops/vblog/middleware"
	"github.com/infraboard/mcube/v2/ioc"
	"github.com/infraboard/mcube/v2/ioc/config/datasource"
)

func init() {
	ioc.Controller().Registry(&BlogServiceImpl{})
}

var _ blog.Service = (*BlogServiceImpl)(nil)

type BlogServiceImpl struct {
	ioc.ObjectImpl
}

func (*BlogServiceImpl) Name() string {
	return blog.AppName
}

// CreateBlog implements blog.Service.
func (b *BlogServiceImpl) CreateBlog(ctx context.Context, in *blog.CreateBlogRequest) (*blog.Blog, error) {
	ins, err := blog.NewBlog(in)
	if err != nil {
		return nil, err
	}
	// 从上下文中补充创建人
	tk := middleware.GetTokenFromCtx(ctx)
	ins.CreateBy = tk.RefUserName

	// 存数据
	if err := datasource.DBFromCtx(ctx).Create(ins).Error; err != nil {
		return nil, err
	}
	return ins, nil
}

// DeleteBlog implements blog.Service.
func (b *BlogServiceImpl) DeleteBlog(context.Context, *blog.DeleteBlogRequest) error {
	panic("unimplemented")
}

// DescribeBlog implements blog.Service.
func (b *BlogServiceImpl) DescribeBlog(context.Context, *blog.DescribeBlogRequest) (*blog.Blog, error) {
	panic("unimplemented")
}

// PublishBlog implements blog.Service.
func (b *BlogServiceImpl) PublishBlog(context.Context, *blog.PublishBlogRequest) (*blog.Blog, error) {
	panic("unimplemented")
}

// QueryBlog implements blog.Service.
func (b *BlogServiceImpl) QueryBlog(ctx context.Context, in *blog.QueryBlogRequest) (*blog.BlogSet, error) {
	// 查询条件
	query := datasource.DBFromCtx(ctx).Model(&blog.Blog{})
	if in.KeyWords != "" {
		query = query.Where("title LIKE ?", "%"+in.KeyWords+"%")
	}
	if in.CreateBy != "" {
		query = query.Where("create_by = ?", in.CreateBy)
	}
	if in.Category != "" {
		query = query.Where("category = ?", in.Category)
	}
	if in.Stage != nil {
		query = query.Where("stage = ?", in.Stage)
	}
	for k, v := range in.Tags {
		query = query.Where(fmt.Sprintf("tags->>'$.%s' = ?", k), v)
	}
	set := blog.NewBlogSet()
	// 查询总数
	if err := query.Count(&set.Total).Error; err != nil {
		return nil, err
	}

	// 处理分页
	err := query.Order("created_at DESC").Offset(int(in.Offset())).Limit(int(in.PageSize)).Find(&set.Items).Error
	if err != nil {
		return nil, err
	}
	return set, nil
}

// UpdateBlog implements blog.Service.
func (b *BlogServiceImpl) UpdateBlog(context.Context, *blog.UpdateBlogRequest) (*blog.Blog, error) {
	panic("unimplemented")
}
